package com.wfh.rpc.server.tcp;

import com.wfh.rpc.server.Server;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.net.NetServer;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

/**
 * @Title: VertxTcpServer
 * @Author wangfenghuan
 * @Package com.wfh.rpc.server.tcp
 * @Date 2025/10/14 21:21
 * @description: 服务端
 */
@Slf4j
public class VertxTcpServer implements Server {

    private byte[] handleRequest(byte[] requestData){
        return "hello".getBytes(StandardCharsets.UTF_8);
    }

    /**
     * 启动服务
     * @param port
     */
    @Override
    public void doStart(int port) {
        // 创建vertx实例
        Vertx vertx = Vertx.vertx();
        NetServer server = vertx.createNetServer();
        // 处理请求
        server.connectHandler(netSocket -> {
            // 处理连接
            netSocket.handler(buffer -> {
                // 处理接收到的字节数组
                byte[] requestData = buffer.getBytes();
                // 这里自定义字节数组的处理逻辑
                byte[] responseData = handleRequest(requestData);
                // 发送响应
                netSocket.write(Buffer.buffer(requestData));
            });
        });

        // 启动tcp服务，并监听指定的端口
        server.listen(port, netServerAsyncResult -> {
            if (netServerAsyncResult.succeeded()){
                log.info("tcp server started on port: {}", port);
            }else {
                log.error("server start failed: {}", netServerAsyncResult.cause().toString());
            }
        });
    }

    public static void main(String[] args) {
        new VertxTcpServer().doStart(8888);
    }
}
